//
//  ViewController.m
//  19-JSON网易
//
//  Created by 鹏飞罗 on 16/8/9.
//  Copyright © 2016年 罗鹏飞. All rights reserved.
//

#import "ViewController.h"
#import "newsTitle.h"
#import "CustomCollectionViewLayout.h"
#import "NewsCollectionViewCell.h"
#define kCollectionViewReuse @"reuse"
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,CustomCollectionViewLayoutDelegate>
@property (nonatomic, strong) NSMutableArray *newsTitleArray;
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self handleData];
    CustomCollectionViewLayout *title = (CustomCollectionViewLayout *)self.myCollectionView.collectionViewLayout;
    title.delegate = self;
    
}
- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout*)collectionViewLayout
                   height:(CGFloat)height
  widthForItemAtIndexPath:(NSIndexPath *)indexPath {
    NewsTitle *title = _newsTitleArray[indexPath.row];
  CGRect newRect = [title.tname boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.myCollectionView.frame)) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
    CGFloat width = ceilf(newRect.size.width);
    return width;
}
- (void)handleData {
    
    _newsTitleArray = [NSMutableArray array];
   NSString *newsJSON = [[NSBundle mainBundle] pathForResource:@"news" ofType:@"json"];
    NSData *JSONData = [NSData dataWithContentsOfFile:newsJSON];
  //JSON解析
    NSError *error = nil;
  NSDictionary *newsTitleDic = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&error];
    NSArray *list = newsTitleDic[@"tList"];
    for (NSDictionary *newsTitle in list) {
        NewsTitle *news = [NewsTitle newsTitleWithDic:newsTitle];
        [_newsTitleArray addObject:news];
       
    }
}
- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _newsTitleArray.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NewsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    
    NewsTitle *news = _newsTitleArray[indexPath.row];
    cell.titleLabel.text = news.tname;
    
    
    
    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
